/**
 * Copyright 2013-2015
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */	  

package com.cos.controller.app.appuser;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cos.controller.app.model.AppGroup;
import com.cos.controller.app.model.Department;
import com.cos.controller.base.BaseController;
import com.cos.service.system.appuser.AppuserService;
import com.cos.util.AppUtil;
import com.cos.util.PageData;
import com.cos.util.ResponseUtil;
import com.cos.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * APP用户的公用接口类
 * <p/>
 * 1.根据用户ID 获取用户拥有的好友  及其组别
 * 2.根据用户ID获取所有该用户的公司
 * 3.根据用户ID获取部门
 * 4.获取工作提议数据
 * 5.获取工作提议详情
 * 6.获取工作自荐列表
 * 7.获取评论列表
 * 8.获取回复
 * 9.获取踩、赞的人
 * @author <a href="mailto:978954852@qq.com">xfjin</a>
 * @version  Date: 2016年3月21日 下午3:51:00
 * @serial 1.0
 * @since 2016年3月21日 下午3:51:00
 */
@Controller
@RequestMapping(value="/appuser")
public class IntAppuserCommenController extends BaseController {
	@Resource(name="appuserService")
	private AppuserService appuserService;
	
	
	/**
	 * 根据用户ID 获取用户拥有的好友  及其组别
	 * @return 
	 * @throws Exception 
	 */
	@RequestMapping(value="/getGroup")
	@ResponseBody
	public String getGroup(HttpServletResponse response) throws Exception{
		logBefore(logger, "根据用户ID获得用户群组");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		JSONObject group=new JSONObject();
		List<AppGroup> appGroupList = new ArrayList<AppGroup>();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getGroup", pd)){	//检查参数
				List<PageData> groupList = new ArrayList<PageData>();
				List<PageData> userList = new ArrayList<PageData>();
			
				groupList = appuserService.getGroup(pd);//根据用户ID取出该用户的组
				for(int i=0;i<groupList.size();i++){
					AppGroup appGroup =  new AppGroup();
					String Group_ID = (String) groupList.get(i).get("ID");
					userList = appuserService.getUserByGroupID(Group_ID);//根据该用户的组取出来下面的用户
					appGroup.setGROUP_ID(Group_ID);
					appGroup.setGROUP_NAME(groupList.get(i).getString("GROUP_NAME"));
					appGroup.setUserList(userList);
					appGroupList.add(appGroup);
				}
				result = (null == pd) ?  "02" :  "01";
			}else {
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			group.put("result", result);
			logAfter(logger);
		}
		JSONArray rows = JSONArray.fromObject(appGroupList);
		group.put("rows", rows);
		ResponseUtil.write(response, group);
		return null;
	}
	
	
	/**
	 * 根据用户ID获取所有该用户的公司
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getCompany")
	@ResponseBody
	public Object getCompanyByUID(HttpServletResponse response) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		JSONObject company = new JSONObject();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getGroup", pd)){	//检查参数
				List<PageData> companyList = new ArrayList<PageData>();
				companyList = appuserService.getCompany(pd);
				JSONArray rows = JSONArray.fromObject(companyList);
				result = "02";
				company.put("rows", rows);
			}else{
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			company.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, company);
		return null;
	}
	

	/**
	 * 根据用户ID获取部门
	 * @param response U_ID用户ID C_ID 公司ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getDepartment")
	@ResponseBody
	public Object getDepartment(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取部门");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject department = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getNoteCompany", pd)){	//检查参数
				List<PageData> departmentList = new ArrayList<PageData>();		
				List<Department> list = new ArrayList<Department>();
				departmentList = appuserService.getDepartment(pd);//查出这个用户的所有部门
				for(int i=0;i<departmentList.size();i++){
					Department d = new Department();
					String departmentID = (String) departmentList.get(i).get("D_ID"); //一个个循环取出部门ID
					d.setID(departmentID);
					d.setNAME((String) departmentList.get(i).get("NAME"));
					d.setPARENT_ID((String) departmentList.get(i).get("PARENT_ID"));
					list.add(d);
					PageData depart = new PageData();
					PageData pp = new PageData();
					
					depart = appuserService.getDepart(departmentID);//通过部门ID取出这个部门的基本信息
					
					String PARENT_ID = (String) depart.get("PARENT_ID");
					if(PARENT_ID.equals("0")){ //
						
					}else{
						Department a = new Department();
						PageData gg = appuserService.getDepartTest(PARENT_ID);//取出父类部门
						a.setID((String) gg.get("ID"));
						a.setNAME((String) gg.get("NAME"));
						a.setPARENT_ID(PARENT_ID);
						list.add(a);
					}
				}
				JSONArray rows = JSONArray.fromObject(list);
				result = (null == departmentList) ?  "02" :  "01";
				department.put("rows", rows);
			}else {
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			department.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, department);
		return null;
	}
	
	/**
	 * 获取工作提议数据
	 * @param response    用户ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getWordAdviceByUID")
	@ResponseBody
	public Object getWordAdviceByUID(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作分工");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject workAdvice = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getWorkPlanByUID", pd)){
				List<PageData> wordAdviceList = new ArrayList<PageData>();
				pd.put("TIME", StringUtil.formatLike((String) pd.get("TIME")));
				wordAdviceList = appuserService.getWordAdvice(pd);
				/*for(int i =0;i<wordAdviceList.size();i++){
					wordAdviceList.get(i).put("RECOMMENT_COUNT", wordAdviceList.get(i).get("(SELECT COUNT(*) from work_recommend  where P_ID = a.ID)"));
					wordAdviceList.get(i).remove("(SELECT COUNT(*) from work_recommend  where P_ID = a.ID)");
				}*/
				pd.put("TIME", StringUtil.formatLike((String) pd.get("TIME")));
				JSONArray rows = JSONArray.fromObject(wordAdviceList);
				result = (null == wordAdviceList) ?  "02" :  "01";
				workAdvice.put("rows", rows);
			}else {
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdvice.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdvice);
		return null;
		
	}
	
	/**
	 * 获取工作提议数据
	 * @param response    部门ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getWordAdviceByDID")
	@ResponseBody
	public Object getWordAdviceByDID(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作分工");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject workAdvice = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getWordPlanByDID", pd)){
				List<PageData> wordAdviceList = new ArrayList<PageData>();
				pd.put("TIME", StringUtil.formatLike((String) pd.get("TIME")));
				wordAdviceList = appuserService.getWordAdvice(pd);
				JSONArray rows = JSONArray.fromObject(wordAdviceList);
				result = (null == wordAdviceList) ?  "02" :  "01";
				workAdvice.put("rows", rows);
			}else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdvice.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdvice);
		return null;
	}
	
	
	/**
	 * 获取工作提议详情
	 * @param response  工作提议的ID //部门D_ID或者用户U_ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getWordAdviceDetail")
	@ResponseBody
	public Object getWordAdviceDetail(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作提议详情");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject workAdviceDetail = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getWorkAdviceID", pd)){//检查参数 
				PageData wordAdvice = new PageData();
				wordAdvice = appuserService.getWordAdviceDetail(pd);
				JSONArray rows = JSONArray.fromObject(wordAdvice);
				result = (null == wordAdvice) ?  "02" :  "01";
				workAdviceDetail.put("rows", rows);
			}else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdviceDetail.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdviceDetail);
		return null;
	}
	
	/**
	 * 获取工作自荐列表
	 * @param response P_ID  工作提议的ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getWorkRecommend")
	@ResponseBody
	public Object getWorkRecommend(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作自荐列表");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject workRecommend = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getWorkAdviceID", pd)){//检查参数 
				List<PageData> wordAdviceList = new ArrayList<PageData>();
				wordAdviceList = appuserService.getWorkRecommend(pd);
				JSONArray rows = JSONArray.fromObject(wordAdviceList);
				result = (null == wordAdviceList) ?  "02" :  "01";
				workRecommend.put("rows", rows);
			}else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workRecommend.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workRecommend);
		return null;
	}
	/**
	 * 发布工作提议
	 * @param response    CONTENT 内容  
	 * 					  STAND   标准
	 * 					  MONEY   钱
	 * 					  START_TIME时间
	 * 					  CREATE_TIME创建时间
	 * 					  U_ID  用户ID
	 * 					  C_ID
	 * 					  D_ID					 				
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping(value="/saveWordAdvice")
	@ResponseBody
	public Object saveWordAdvice(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作分工");
		JSONObject workAdvice = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveWordAdvice", pd)){
				pd.put("ID", this.get32UUID());
				pd.put("SUPPORT_NUM","0");
				pd.put("TRAMPLE_NUM","0");
				appuserService.saveWordAdvice(pd);
				result =  "02";
			}else{ 
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdvice.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdvice);
		return null;
	}
	
	/**
	 * 发布工作自荐
	 * @param response    CONTENT 内容  
	 * 					  CREATE_TIME创建时间
	 * 					  U_ID  用户ID
	 * 					  P_ID   工作提议ID	
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping(value="/saveWorkRecommend")
	@ResponseBody
	public Object saveWordPLAN(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作分工");
		JSONObject workAdvice = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveWorkRecommend", pd)){
				pd.put("ID", this.get32UUID());
				appuserService.saveWorkRecommend(pd);
				result =  "02";
			}else{ 
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdvice.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdvice);
		return null;
	}
	
	/**
	 * 获取评论列表
	 * @param response DT_ID  DT_TYPE动态类型
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getComment")
	@ResponseBody
	public Object getComment(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取评论");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject workRecommend = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getComment", pd)){//检查参数 
				List<PageData> wordAdviceList = new ArrayList<PageData>();
				wordAdviceList = appuserService.getComment(pd);
				JSONArray rows = JSONArray.fromObject(wordAdviceList);
				result = (null == wordAdviceList) ?  "02" :  "01";
				workRecommend.put("rows", rows);
			}else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workRecommend.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workRecommend);
		return null;
	}
	
	/**
	 * 获取回复
	 * @param response COMMENT_ID  评论ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getReply")
	@ResponseBody
	public Object getReply(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取工作评论回复");
		JSONObject workRecommend = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getReply", pd)){//检查参数 
				List<PageData> wordAdviceList = new ArrayList<PageData>();
				wordAdviceList = appuserService.getReply(pd);
				JSONArray rows = JSONArray.fromObject(wordAdviceList);
				result = (null == wordAdviceList) ?  "02" :  "01";
				workRecommend.put("rows", rows);
			}else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workRecommend.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workRecommend);
		return null;
	}
	
	/**
	 * 获取踩、赞的人
	 * @param response DT_TYPE动态类型   DT_ID动态ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getDynamicStatus")
	@ResponseBody
	public Object getDynamicStatus(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取赞踩的人");
		JSONObject workRecommend = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getComment", pd)){//检查参数 
				List<PageData> wordAdviceList = new ArrayList<PageData>();
				wordAdviceList = appuserService.getDynamicStatus(pd);
				JSONArray rows = JSONArray.fromObject(wordAdviceList);
				result = (null == wordAdviceList) ?  "02" :  "01";
				workRecommend.put("rows", rows);
			}else{
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workRecommend.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workRecommend);
		return null;
	}
	    @RequestMapping(value="download")
    public ModelAndView download(HttpServletRequest request,  
            HttpServletResponse response) throws Exception {  
		String Name ="apk.exe" ;
        String contentType = "application/octet-stream" ;  
        IntAppuserCommenController.download(request, response, Name, contentType) ;  
        return null ;  
    }  
	
	//文件下载 主要方法
    public static void download(HttpServletRequest request,  
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception {  
    	
        request.setCharacterEncoding("UTF-8");  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
 
        //获取项目根目录
        String ctxPath = "D:/";  
        
        //获取下载文件露肩
        String downLoadPath = ctxPath+"/uploadFiles/file/apkUpload/"+ storeName;  
  
        //获取文件的长度
        long fileLength = new File(downLoadPath).length();  

        //设置文件输出类型
        response.setContentType("application/octet-stream");  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(storeName.getBytes("utf-8"), "ISO8859-1")); 
        //设置输出长度
        response.setHeader("Content-Length", String.valueOf(fileLength));  
        //获取输入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
        //输出流
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[2048];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }  
        //关闭流
        bis.close();  
        bos.close();  
    }  
    
	@RequestMapping(value="/getpic", method = RequestMethod.GET)
	public String getpic(Model model, HttpServletResponse response) throws IOException {
		response.setContentType("image/jpeg"); // 设置返回内容格式
		File file = new File("D:/uploadFiles/uploadImgs/showTwoDimensonCode.png");       //括号里参数为文件图片路径
		if(file.exists()){   //如果文件存在
			InputStream in = new FileInputStream("D:/uploadFiles/uploadImgs/showTwoDimensonCode.png");   //用该文件创建一个输入流
			OutputStream os = response.getOutputStream();  //创建输出流
			byte[] b = new byte[1024];  
			while( in.read(b)!= -1){ 
			os.write(b);     
			}
			in.close(); 
			os.flush();
			os.close();
		}
		return null;
	}
	
}